<template>
  <div class="app-container">
    <el-row>
      <div style="margin: 4px 0 20px 4px;">
        <span style="font-size: 20px; font-weight: bold">{{ template.name }}</span>
      </div>
    </el-row>
    <div style="margin: 20px 0px 20px 4px;">
      <span style="font-size: 20px; font-weight: bold">表头信息</span>
    </div>
    <el-card class="box-card">
      <div v-if="chooseHeader !== null">
        <div v-if="chooseHeader.json==null">
          <tenkvHeader ref="Header" :header-form-origin="headerFormOrigin"/>
        </div>
        <div v-else-if="chooseHeader.hasOwnProperty('json')">
          <v-form-render ref="Header" :form-data="headerFormOrigin" :form-json="getClearFormJson(chooseHeader.json)"/>
        </div>
      </div>
    </el-card>
    <el-row>
      <div style="margin: 20px 0px 20px 4px;">
        <span style="font-size: 20px; font-weight: bold">表单项</span>
      </div>
    </el-row>
    <el-card v-loading="listLoading">
      <div v-for="(item,index) in bodyRenderList" :key="index" style="margin: 12px 0;">
        <custom-question-block v-if="item.json==null"
                               v-model="bodyModelValue[`${item.oid}`]"
                               :question-block="item" :order="false"/>
        <v-form-render v-else :form-json="getClearFormJson(item.json)"
                       :ref="`${item.oid}`"  :form-data="bodyModelValue[`${item.oid}`].retData"/>
      </div>
    </el-card>
    <el-row>
      <div style="margin: 20px 0px 20px 4px;">
        <span style="font-size: 20px; font-weight: bold">表尾信息</span>
      </div>
    </el-row>
    <el-card>
      <div v-if="chooseTail !== null">
        <div v-if="chooseTail.json==null">
          <tenkvTail ref="Tail" :tail-form="tailForm"/>
        </div>
        <div v-else-if="chooseTail.hasOwnProperty('json')">
          <v-form-render ref="Tail" :form-data="tailForm" :form-json="getClearFormJson(chooseTail.json)"/>
        </div>
      </div>
    </el-card>
    <el-row>
      <div style="margin: 20px 0px 20px 4px;">
        <span style="font-size: 20px; font-weight: bold">附件上传</span>
      </div>
    </el-row>
    <el-card v-loading="fileLoading">
      <el-table
        v-loading="listLoading"
        :data="fileData"
        style="width: 100%"
        border
      >
        <el-table-column
          width="82"
          label="id"
          prop="fid"
        />
        <el-table-column
          label="文件名"
          prop="realname"
        />

        <el-table-column align="center" width="242">
          <template slot="header" slot-scope="scope">
            <div style="width: 100%;text-align: center;">
              <el-button slot="trigger" size="small" type="primary" @click="upFile">添加文件</el-button>
              <input ref="singleFile" type="file" style="display: none;" @change="handleFileUpload($event)">
            </div>

          </template>
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleDownload(scope.row.realname,scope.row.path)"
            >下载</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row.fid)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-row style="margin: 24px 0px 24px 0px;">
      <el-form :inline="true" style="display: flex; justify-content: center;">
        <el-button type="primary" :plain="true" @click="saveDraft">保存草稿</el-button>
        <el-button type="primary" @click="submitDialogFormVisible = true">提交</el-button>
        <el-button @click="$router.push({path:'/workOrderSys/myDraft'})">取消</el-button>
      </el-form>
    </el-row>
    <el-dialog title="提交新工单" :visible.sync="submitDialogFormVisible">
      <el-form ref="ruleForm" :model="queryUser" status-icon class="demo-ruleForm" style="margin-left: 12px">
        <el-form-item>
          <span>该操作将提交工单进入流转状态，请确认工单是否正确填写。</span>
        </el-form-item>
        <el-form-item label="工单流转至:">
          <el-input v-model="queryUser.keyword" placeholder="请输入姓名或工号" style="width: 200px;"
                    prefix-icon="el-icon-search"
                    size="small"
                    @keyup.enter.native="searchUser(1)"
          />
          <el-button type="primary" icon="el-icon-search" size="small" style="margin-left: 12px" @click="searchUser(1)">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="listLoading"
        :data="searchList"
        style="width: 100%"
      >
        <el-table-column
          label="工号"
          prop="uid"
        />
        <el-table-column
          label="姓名"
          prop="username"
        />
        <el-table-column
          align="right"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleTo(scope.row.uid)"
            >流转给TA</el-button>
          </template></el-table-column>
      </el-table>
      <div style="width: 100%;text-align: center;margin:24px 0 0 0;">
        <el-pagination
          :page-size="5"
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          :total="total"
          @current-change="searchUser(currentPage)"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleTo($store.getters.userInfo.uid)">流转给自己</el-button>
        <el-button type="primary" @click="handleToStore($store.getters.userInfo.uid)">流转为自由表单</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CustomRadio from '@/components/CustomRadio'
import {
  deleteDraft,
  deleteFile,
  getFile,
  getTemplateBody, getTemplateHeader, getTemplateTail,
  modifyDraft,
  publishDraft,
  uploadOrderFile
} from '@/api/table'
import {getClearFormJson, MAPPER, PAGE_SIZES} from '@/utils/common'
import CustomQuestionBlock from '@/components/CustomQuestionBlock'
import { spheader, handleHeader, sptail, reverseHeader, headerFormOrigin } from '@/utils/fix/pre'
import { findUser } from '@/api/user'
import { BASE_URL } from '@/utils/request'
import { publishDraftAsFree } from '../../api/table'
import tenkvHeader from "@/components/fixedForm/tenkvHeader.vue";
import tenkvTail from "@/components/fixedForm/tenkvTail.vue";
const allComponents = require.context('@/components/CustomQuestionBlock/questions', false, /\.vue$/)
const res_components = {}
allComponents.keys().forEach(fileName => {
  const comp = allComponents(fileName)
  res_components[fileName.replace(/^\.\/(.*)\.\w+$/, '$1')] = comp.default
})
export default {
  components: {tenkvTail, tenkvHeader, CustomRadio, ...res_components, CustomQuestionBlock },
  name: 'EditDraft',
  data() {
    return {
      bodyTemplates: [],
      headerTemplates:[],
      tailTemplates:[],
      chooseHeader: null,
      chooseTail: null,
      fileLoading: false,
      searchList: [],
      currentPage: 1,
      pageSize: PAGE_SIZES,
      total: 0,
      MAPPER: MAPPER,
      headerFrom: { ...spheader },
      tailForm: { ...sptail },
      queryUser: {
        keyword: '',
        status: '',
        dateRange: []
      },
      list: [],
      listLoading: false,
      fileList: [],
      headerFormOrigin: {},
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      orgNum: '',
      id: '',
      saveDialogFormVisible: false,
      submitDialogFormVisible: false,
      template: { body_list: [] },
      bodyModelValue: {},
      fileData: [],
      bodyRenderList: [],
    }
  },
  async created() {
    //获取所有的body_list
    try {
      const [bodyResponse, headerResponse, tailResponse] = await Promise.all([
        getTemplateBody(),
        getTemplateHeader(),
        getTemplateTail()
      ]);
      this.bodyTemplates = bodyResponse.data.data;
      this.headerTemplates = headerResponse.data.data;
      this.tailTemplates = tailResponse.data.data;
    } catch (error) {
      console.error('发生错误：', error);
    }
    const data = this.$route.params.draft
    if (data) {
      this.template = data
      this.chooseHeader = this.headerTemplates.find((item) => {
        return item.oid === this.template.header_id
      })
      this.chooseTail = this.tailTemplates.find((item) => {
        return item.oid === this.template.tail_id
      })
      if(this.chooseHeader.json==null){
        this.headerFormOrigin = {...reverseHeader(this.template.header_value)}
      }else{
        this.headerFormOrigin = JSON.parse(this.template.header_value).retData
      }

      if(this.chooseTail.json==null) {
        this.tailForm = JSON.parse(this.template.tail_value)
      }else{
        this.tailForm = JSON.parse(this.template.tail_value).retData
      }
      this.bodyModelValue = JSON.parse(data.body_value)
      this.template.body_list.forEach((item, index) => {
        const find = this.bodyTemplates.find(i => i.oid === item)
        this.bodyRenderList.push(find)
      })
      getFile(this.template.tid).then(res => {
        this.fileData = res.data
      })
    } else {
      this.$router.push('/workOrderSys/myDraft')
    }
  },
  methods: {
    getClearFormJson,
    handleDownload(fileName, path) {
      const url = BASE_URL + path
      const el = document.createElement('a')
      el.style.display = 'none'
      el.setAttribute('target', '_blank')
      /**
       * download的属性是HTML5新增的属性
       * href属性的地址必须是非跨域的地址，如果引用的是第三方的网站或者说是前后端分离的项目(调用后台的接口)，这时download就会不起作用。
       * 此时，如果是下载浏览器无法解析的文件，例如.exe,.xlsx..那么浏览器会自动下载，但是如果使用浏览器可以解析的文件，比如.txt,.png,.pdf....浏览器就会采取预览模式
       * 所以，对于.txt,.png,.pdf等的预览功能我们就可以直接不设置download属性(前提是后端响应头的Content-Type: application/octet-stream，如果为application/pdf浏览器则会判断文件为 pdf ，自动执行预览的策略)
       */
      fileName && el.setAttribute('download', fileName)
      el.href = url
      console.log(el)
      document.body.appendChild(el)
      el.click()
      document.body.removeChild(el)
    },
    handleDelete(fid) {
      this.$confirm('此操作将删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteFile(fid).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          getFile(this.template.tid).then(res => {
            this.fileData = res.data
          })
        })
      })
    },
    getBodyValue() {
      for(let item of this.bodyRenderList){
        if(item.json!=null){
          this.bodyModelValue[`${item.oid}`] = this.$refs[`${item.oid}`][0].getFormData(false)
        }
      }
    },
    upFile() {
      this.$refs.singleFile.click()
    },
    handleFileUpload(event) {
      event.preventDefault()
      const formData = new FormData()
      const file = this.$refs.singleFile.files[0]
      formData.append('file', file)
      this.onUpload(formData)
    },
    onUpload(formData) {
      uploadOrderFile(formData, this.template.tid).then((res) => {
        this.$message.success('上传成功')
        getFile(this.template.tid).then(res => {
          this.fileData = res.data
        })
      }).catch((e) => {
        this.$message.error('上传失败')
      })
    },
    handleToStore(uid) {
      this.getBodyValue()
      const header = this.$refs.Header.getFormData(false)
      this.template.body_list.forEach((item, index) => {
        this.bodyModelValue[item].num = index + 1
        this.bodyModelValue[item]['fe'] = ''
      })
      const data = {
        name: header.projectName||header.retData.projectName,
        handler: uid,
        header_id: this.template.header_id,
        header_value: header,
        body_list: this.template.body_list,
        body_value: this.bodyModelValue,
        tail_id: this.template.tail_id,
        tail_value: this.$refs.Tail.getFormData(false)
      }
      const tid = this.template.tid
      modifyDraft(tid, data).then(async res => {
        await publishDraftAsFree(tid)
        this.$message.success('发布表单成功')
        this.$router.go(-1)
      })
    },
    handleTo(uid) {
      this.getBodyValue()
      const header = this.$refs.Header.getFormData(false)
      this.template.body_list.forEach((item, index) => {
        this.bodyModelValue[item].num = index + 1
        this.bodyModelValue[item]['fe'] = ''
      })
      const data = {
        name: header.projectName||header.retData.projectName,
        handler: uid,
        header_id: this.template.header_id,
        header_value: header,
        body_list: this.template.body_list,
        body_value: this.bodyModelValue,
        tail_id: this.template.tail_id,
        tail_value: this.$refs.Tail.getFormData(false)
      }
      const tid = this.template.tid
      modifyDraft(tid, data).then(async res => {
        await publishDraft(tid)
        this.$message.success('发布表单成功')
        this.$router.go(-1)
      })
    },
    searchUser(page) {
      this.listLoading = true
      findUser(5, page, { name: this.queryUser.keyword }).then(response => {
        this.searchList = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleChange(file, fileList) {
      this.fileList = fileList
      const isLt5M = file.size / 1024 / 1024 > 20
      if (isLt5M) {
        this.$message.error(this.$t('images_size'), 'error')
        const currIdx = this.fileList.indexOf(file)
        this.fileList.splice(currIdx, 1)
      }
    },
    saveDraft() {
      this.getBodyValue()
      const header = this.$refs.Header.getFormData(false)
      this.template.body_list.forEach((item, index) => {
        this.bodyModelValue[item].num = index + 1
      })
      const data = {
        name: header.projectName||header.retData.projectName,
        handler: this.$store.getters.userInfo.uid,
        header_id: this.template.header_id,
        header_value: header,
        body_list: this.template.body_list,
        body_value: this.bodyModelValue,
        tail_id: this.template.tail_id,
        tail_value: this.$refs.Tail.getFormData(false)
      }
      const tid = this.template.tid
      modifyDraft(tid, data).then(res => {
        this.$message.success('保存表单草稿成功')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.line {
  text-align: center;
}

</style>

